package com.imut.onlinebanking.user.controller;

import com.imut.onlinebanking.user.mapper.UserMapper;
import com.imut.onlinebanking.user.pojo.entity.User;
import com.imut.onlinebanking.user.mapper.LoginMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class RegisterController {

    @Autowired
    private UserMapper userMapper;

    @PostMapping("/register")
    public ResponseEntity<Map<String, Object>> register(@RequestBody User user) {
        Map<String, Object> response = new HashMap<>();

        // 1. 校验用户名是否已存在
        if (userMapper.selectByUsername(user.getUsername()) != null) {
            response.put("code", 4001);
            response.put("msg", "用户名已存在");
            return ResponseEntity.badRequest().body(response);
        }

        // 2. 插入新用户
        try {
            userMapper.insertUser(user); //  使用 UserMapper 的 insertUser
        } catch (Exception e) {
            response.put("code", 5000);
            response.put("msg", "注册失败：" + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }

        // 3. 注册成功
        response.put("code", 2000);
        response.put("msg", "注册成功");
        response.put("data", "/index.html");

        return ResponseEntity.ok(response);
    }
}
